package com.app.util.args;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.app.util.string.StringUtil;


public class Args {

	List<String> args;
	Map<String, String> options;

	public Args(String[] args) {

		List<String> argsList = new ArrayList<String>();
		Map<String, String> options = new LinkedHashMap<String, String>();

		if (args.length != 0) {
			for (int i = 0; i < args.length; i++) {
				if (args[i].charAt(0) == '-' && args[i].length() > 1) {
					if (args[i].indexOf("=") != -1) {
						options.put(StringUtil.getLeft(args[i], "="), StringUtil.getRightOuter(args[i], "="));
					} else if (i < args.length - 1 && args[i + 1].charAt(0) != '-') {
						options.put(args[i], args[i + 1]);
						i++;
					} else {
						options.put(args[i], "");
					}
				} else {
					argsList.add(args[i]);
				} 
			}
		}

		this.args = (List<String>) Collections.unmodifiableList(argsList);
		this.options = Collections.unmodifiableMap(options);
	}

	public List<String> getArgs() {
		return args;
	}

	public String getArg(int i) {
		return getArg(i, "");
	}

	public String getArg(int i, String defaultValue) {
		if (i >= args.size() || StringUtil.isTrimEmpty(args.get(i))) {
			return defaultValue;
		}
		return args.get(i);
	}

	public Map<String, String> getOptions() {
		return options;
	}

	public boolean containsOption(String opt) {
		return options.containsKey(opt);
	}

	public String getOptionValue(String opt) {
		return getOptionValue(opt, "");
	}

	public String getOptionValue(String opt, String defaultValue) {
		if (StringUtil.isTrimEmpty(options.get(opt))) {
			return defaultValue;
		}
		return options.get(opt);
	}

	public String toString() {
		StringBuffer sb = new StringBuffer();
		for (String arg : args) {
			sb.append(arg).append(" ");
		}
		for (Entry<String, String> argEnt : options.entrySet()) {
			sb.append(argEnt.getKey()).append("=").append(argEnt.getValue()).append(" ");
		}
		return sb.toString();
	}
}